package com.hk.rabbitmq.controller;

import com.hk.rabbitmq.config.DelayedQueueConfig;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import java.util.Date;

/**
 * @author: dpb
 * @date: 2022/3/25
 */
@Slf4j
@RestController
@RequestMapping("ttl")
@Api(value = "/ttl",tags = "发送延迟消息接口")
public class SendMsgController {

    @Autowired
    private RabbitTemplate rabbitTemplate;


    @GetMapping("sendMsg/{message}")
    public void sendMsg(@PathVariable("message") String message){
        log.info("当时时间：{},发送一条信息给两个TTL队列:{}",new Date(),message);
        rabbitTemplate.convertAndSend("X","XA","消息来自TTL为10s的队列：" + message);
        rabbitTemplate.convertAndSend("X","XB","消息来自TTL为40s的队列：" + message);
    }

    @GetMapping("sendExpirationMsg/{message}/{ttlTime}")
    public void sendMsg(@PathVariable("message") String message,
                        @PathVariable("ttlTime") String ttlTime){
        rabbitTemplate.convertAndSend("X", "XC", message, msg -> {
            msg.getMessageProperties().setExpiration(ttlTime);
            return msg;
        });
        log.info("当前时间：{}，发送一条时长{}毫秒TTL信息给队列C：{}", new Date(), ttlTime, message);
    }

    /**
     * 基本于插件的发消息，实现延迟队列
     * @param message
     * @param delayTime
     */
    @ApiOperation(value = "sendDelayMsg/{message}/{delayTime}",tags = "基本于插件的发消息，实现延迟队列")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "message", value = "要发送的消息", required = true),
            @ApiImplicitParam(name = "delayTime", value = "延迟多久发送", required = true)
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "返回成功")
    })
    @GetMapping("sendDelayMsg/{message}/{delayTime}")
    public void sendMsg(@PathVariable("message") String message,
                        @PathVariable("delayTime") Integer delayTime){
        rabbitTemplate.convertAndSend(DelayedQueueConfig.DELAYED_EXCHANGE_NAME, DelayedQueueConfig.DELAYED_ROUTING_KEY, message, msg -> {
            msg.getMessageProperties().setDelay(delayTime);
            return msg;
        });
        log.info("当前时间：{}，发送一条【延迟】{}毫秒TTL信息给队列C：{}", new Date(), delayTime, message);
    }


}
